//#include	"unp.h"
#include	<time.h>
#include	<stdio.h>
#include	<strings.h>
#include	<string.h>
#include 	<sys/socket.h>
#include 	<netinet/in.h>

#define	PORTA_SERVIDOR 		2335
#define LISTENQ				1024
#define	SA 					struct sockaddr

int main(int argc, char **argv) {
	
	int	listenfd, connfd;  /* listenf - socket que fica ouvindo, connfd - socket para conexão */
	socklen_t len;
	struct sockaddr_in 	servaddr, cliaddr;
	
	char buf[256];
	
	listenfd = socket(AF_INET, SOCK_STREAM, 0);  /* criação do socket listen*/

	bzero(&servaddr, sizeof(servaddr));
	
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(PORTA_SERVIDOR);	

	bind(listenfd, (SA *) &servaddr, sizeof(servaddr));  /* Associa uma porta da máq local com o socket */

	listen(listenfd, LISTENQ);   /* Numero de conexões que serão permitidas no socket */
	
	for ( ; ; ){		
		len = sizeof(cliaddr);
		connfd = accept(listenfd, (SA *) &cliaddr, &len);
		bzero(buf, sizeof(buf)); 
		printf("Conexão oriunda de %s , porta %d \n" ,
				inet_ntop (AF_INET, &cliaddr.sin_addr, buf, sizeof(buf)), 
				ntohs (cliaddr.sin_port) );
		
		bzero(buf, sizeof(buf));  

		read(connfd, buf, 256);
		printf("%s\n\n " , buf);
		write(connfd, buf, sizeof(buf));
		
		//bzero(buf, sizeof(256));  

		close(connfd);
		
	}

}
